import { useMainStore, useUserStore } from '@/store'
import { clearPending } from '@/axios/tool/cancelRequest'
import { backstageRoutes, exceptionRoutes } from './modules'

export const createRouterGuards = router => {
  const mainStore = useMainStore()
  const userStore = useUserStore()
  const whitePathList = ['/', '/chat/new', '/wxlogin']
  router.beforeEach(async (to, from, next) => {
    clearPending()
    $loadingBar.start()
    const token = localStorage.getItem('token') || null
    if (token && !userStore.role) {
      await userStore.getUserInfo()
    }
    if (whitePathList.includes(to.path)) return next()
    if (!token) return userStore.logout()
    if (mainStore.isAddedRoute) return next()
    // 动态添加路由
    const routesArr = [...backstageRoutes, ...exceptionRoutes]
    routesArr.forEach(item => router.addRoute(item))
    mainStore.setIsAddedRoute(true)
    next({ ...to, replace: true })
  })

  router.afterEach(to => {
    document.title = to?.meta?.title ? `${mainStore.pageTitle} | ${to?.meta?.title}` : document.title
    $loadingBar.finish()
  })
}
